var express = require('express')
var app = express()
var http = require('http')
var config = require('../config')
var session = require('express-session')
var cookieParser = require('cookie-parser')
var bodyParser = require('body-parser')

const chalk = require('chalk')
const log = console.log
const warning = chalk.keyword('orange')
const error = chalk.bold.red

/// ////// 加载中间件 //////////////////////////////////////
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: false }))
app.use(cookieParser())
app.use(session({
  key: config.sessionConfig.name,
  name: config.sessionConfig.name,
  secret: config.sessionConfig.secret,
  resave: false,
  saveUninitialized: true,
  cookie: {
    secure: false, // true表示https
    domain: config.sessionConfig.domain
  }
}))
/// /////////// ajax代理和转发 //////////////////////////////////////
var proxy = require('./proxy')
// form表单、文件上传的接口用这种代理会更方便//  使用前缀/ajax/proxy
app.use('/ajax/proxy', proxy())

app.use(/^\/guojihua/i, proxy({ // 国际化的转发
  ajaxHost: config.i18nHost,
  json: true,
  key: 'guojihua'
}))

app.use(/^\/export/i, proxy({ // 导出文件
  ajaxHost: config.exportHost,
  key: 'export'
}))
app.use('/favicon.ico', function (req, res) {
  res.end()
})
app.get('/health', function (req, res) { // 健康检查
  return res.status(200).send('OK')
})
app.use(/^\/ajax/i, require('./ajax'))// ajax转发

/// ///////////////// sso相关 ////////////////////////////////////////
let sso = require('./sso')
app.use('/tologinurl', function (req, res) { // 客户端判断未登录后的调整地址
  var url = sso.getSSOLoginUrl(req)
  res.redirect(url)
})
app.use(/^\/page-[\w-]+|(^\/$)/i, function (req, res, next) { // 需要登录的页面
  sso.checkLogin(req, res, next)
})

/// //////////  其他路由控制  ///////////////////////////
app.use('/', require('connect-history-api-fallback')())
app.use('/', express.static('public'))

/// //////////// 开发环境热更新打包 //////////////////////////
if (process.env.NODE_ENV === 'dev') {
  var webpack = require('webpack')
  var webpackConfig = require('../build/webpack.dev.config.js')
  var webpackCompiled = webpack(webpackConfig)
  // 配置运行时打包
  var webpackDevMiddleware = require('webpack-dev-middleware')
  app.use(webpackDevMiddleware(webpackCompiled, {
    publicPath: '/',
    stats: { colors: true },
    lazy: false,
    watchOptions: {
      aggregateTimeout: 300
    }
  }))
  var webpackHotMiddleware = require('webpack-hot-middleware')
  app.use(webpackHotMiddleware(webpackCompiled))
}

/// ///////////  启动服务  /////////////////////
http.createServer(app).listen(config.port, function () {
  console.log('-------------------------')
  log(chalk.blue('Your application is running here:'))

  log(warning('当前监听端口：', config.port))
  log(warning('当前环境：', config.env))
  log(warning('当前cookie所在域：', config.sessionConfig && config.sessionConfig.domain))

  log('--------------------------')

  console.log('Open http://localhost:%s', config.port)
})

// 错误捕获
app.use(function (err, req, res, next) {
  log(error('错误信息:', err))
  log(error('错误信息请求地址:', req.originalUrl))
  console.log('------------------------------------------')
  res.end('An unknown error. Please try again.')
})
